// ==================================================
// 俄罗斯方块完整代码（顺序已调整，可直接替换）
// ==================================================

// 方块形状和颜色定义
const TETRIS_SHAPES = [
    [[1, 1, 1, 1]], // I
    [[1, 1, 1], [0, 1, 0]], // T
    [[1, 1, 1], [1, 0, 0]], // L
    [[1, 1, 1], [0, 0, 1]], // J
    [[0, 1, 1], [1, 1, 0]], // S
    [[1, 1, 0], [0, 1, 1]], // Z
    [[1, 1], [1, 1]]        // O
];

const TETRIS_COLORS = [
    '#00ffff', // 亮青
    '#9c27b0', // 深紫
    '#ff9800', // 亮橙
    '#2196f3', // 亮蓝
    '#4caf50', // 亮绿
    '#f44336', // 亮红
    '#ffeb3b'  // 亮黄
];

// 游戏变量
let tetrisBoard = Array(20).fill().map(() => Array(10).fill(0));
let currentPiece = null;
let currentX = 0;
let currentY = 0;
let tetrisScore = 0;
let tetrisLines = 0;
let tetrisInterval = null;
let isPaused = false;

// DOM 元素
let tetrisCanvas = null;
let tetrisCtx = null;
let tetrisScoreEl = null;
let tetrisLinesEl = null;

// ==================================================
// 工具函数（放在前面定义）
// ==================================================

/**
 * 生成随机方块
 */
function generateRandomPiece() {
    const type = Math.floor(Math.random() * TETRIS_SHAPES.length);
    return {
        shape: TETRIS_SHAPES[type],
        color: TETRIS_COLORS[type]
    };
}

/**
 * 检查碰撞
 */
function checkCollision(piece, offsetX = 0, offsetY = 0) {
    for (let y = 0; y < piece.shape.length; y++) {
        for (let x = 0; x < piece.shape[y].length; x++) {
            if (piece.shape[y][x]) {
                const newX = currentX + x + offsetX;
                const newY = currentY + y + offsetY;
                if (
                    newX < 0 || newX >= 10 ||
                    newY >= 20 ||
                    (newY >= 0 && tetrisBoard[newY][newX])
                ) {
                    return true;
                }
            }
        }
    }
    return false;
}

/**
 * 绘制单个方块
 */
function drawCell(x, y, color) {
    const size = 30;
    tetrisCtx.fillStyle = color;
    tetrisCtx.fillRect(x * size, y * size, size - 1, size - 1);
    tetrisCtx.strokeStyle = 'rgba(0,0,0,0.1)';
    tetrisCtx.strokeRect(x * size, y * size, size - 1, size - 1);
}

// ==================================================
// 游戏逻辑函数
// ==================================================

/**
 * 生成新方块
 */
function spawnPiece() {
    currentPiece = generateRandomPiece();
    currentX = 3;
    currentY = -2;

    if (checkCollision(currentPiece)) {
        clearInterval(tetrisInterval);
        alert('游戏结束！得分：' + tetrisScore);
    }
}

/**
 * 旋转方块
 */
function rotatePiece() {
    const rotated = [];
    for (let i = 0; i < currentPiece.shape[0].length; i++) {
        const row = [];
        for (let j = currentPiece.shape.length - 1; j >= 0; j--) {
            row.push(currentPiece.shape[j][i]);
        }
        rotated.push(row);
    }
    const previousShape = currentPiece.shape;
    currentPiece.shape = rotated;

    // 如果旋转后碰撞，尝试偏移修正
    if (checkCollision(currentPiece)) {
        if (!checkCollision(currentPiece, 1, 0)) {
            currentX += 1;
        } else if (!checkCollision(currentPiece, -1, 0)) {
            currentX -= 1;
        } else if (!checkCollision(currentPiece, 0, 1)) {
            currentY += 1;
        } else {
            currentPiece.shape = previousShape;
        }
    }
}

/**
 * 锁定当前方块到棋盘
 */
function lockPiece() {
    for (let y = 0; y < currentPiece.shape.length; y++) {
        for (let x = 0; x < currentPiece.shape[y].length; x++) {
            if (currentPiece.shape[y][x]) {
                const boardY = currentY + y;
                if (boardY < 0) {
                    clearInterval(tetrisInterval);
                    alert('游戏结束！得分：' + tetrisScore);
                    return false;
                }
                tetrisBoard[boardY][currentX + x] = currentPiece.color;
            }
        }
    }
    clearLines();
    spawnPiece();
    return true;
}

/**
 * 消除已满的行
 */
function clearLines() {
    let linesCleared = 0;
    for (let y = 19; y >= 0; y--) {
        if (tetrisBoard[y].every(cell => cell !== 0)) {
            tetrisBoard.splice(y, 1);
            tetrisBoard.unshift(Array(10).fill(0));
            linesCleared++;
            y++;
        }
    }
    if (linesCleared > 0) {
        tetrisLines += linesCleared;
        tetrisScore += linesCleared * 100;
        updateTetrisUI();
    }
}

// ==================================================
// UI 更新函数
// ==================================================

/**
 * 更新分数和行数显示
 */
function updateTetrisUI() {
    tetrisScoreEl.textContent = tetrisScore;
    tetrisLinesEl.textContent = tetrisLines;
    drawTetris();
}

/**
 * 绘制整个游戏
 */
function drawTetris() {
    tetrisCtx.fillStyle = '#111';
    tetrisCtx.fillRect(0, 0, tetrisCanvas.width, tetrisCanvas.height);

    // 绘制棋盘
    for (let y = 0; y < 20; y++) {
        for (let x = 0; x < 10; x++) {
            if (tetrisBoard[y][x]) {
                drawCell(x, y, tetrisBoard[y][x]);
            }
        }
    }

    // 绘制当前方块
    if (currentPiece) {
        for (let y = 0; y < currentPiece.shape.length; y++) {
            for (let x = 0; x < currentPiece.shape[y].length; x++) {
                if (currentPiece.shape[y][x]) {
                    drawCell(currentX + x, currentY + y, currentPiece.color);
                }
            }
        }
    }
}

// ==================================================
// 游戏控制函数
// ==================================================

/**
 * 移动方块
 */
function movePiece(dir) {
    if (checkCollision(currentPiece, dir, 0)) return;
    currentX += dir;
    updateTetrisUI();
}

/**
 * 下落方块
 */
function dropPiece() {
    if (isPaused) return;

    if (checkCollision(currentPiece, 0, 1)) {
        if (!lockPiece()) return;
    } else {
        currentY++;
    }
    updateTetrisUI();
}

/**
 * 快速下落
 */
function hardDrop() {
    while (!checkCollision(currentPiece, 0, 1)) {
        currentY++;
    }
    lockPiece();
    updateTetrisUI();
}

/**
 * 开始游戏
 */
function startTetris() {
    if (tetrisInterval) return;
    isPaused = false;
    tetrisInterval = setInterval(dropPiece, 1000);
}

/**
 * 暂停游戏
 */
function pauseTetris() {
    isPaused = !isPaused;
}

/**
 * 重置游戏
 */
function resetTetris() {
    clearInterval(tetrisInterval);
    tetrisInterval = null;
    tetrisBoard = Array(20).fill().map(() => Array(10).fill(0));
    tetrisScore = 0;
    tetrisLines = 0;
    isPaused = false;
    spawnPiece();
    updateTetrisUI();
}

// ==================================================
// 事件监听
// ==================================================

/**
 * 键盘控制
 */
function handleTetrisKeydown(e) {
    if (!currentPiece) return;

    switch (e.key) {
        case 'ArrowLeft':
            movePiece(-1);
            break;
        case 'ArrowRight':
            movePiece(1);
            break;
        case 'ArrowDown':
            dropPiece();
            break;
        case 'ArrowUp':
            rotatePiece();
            updateTetrisUI();
            break;
        case ' ':
            hardDrop();
            break;
    }
}

// ==================================================
// 初始化 & 清理
// ==================================================

/**
 * 初始化俄罗斯方块游戏
 */
function initTetrisGame() {
    tetrisCanvas = document.getElementById('tetris-canvas');
    tetrisScoreEl = document.getElementById('tetris-score');
    tetrisLinesEl = document.getElementById('tetris-lines');

    if (!tetrisCanvas || !tetrisScoreEl || !tetrisLinesEl) {
        console.error('俄罗斯方块DOM元素缺失！');
        return;
    }

    // 设置画布尺寸
    tetrisCanvas.width = 300;
    tetrisCanvas.height = 600;
    tetrisCtx = tetrisCanvas.getContext('2d');

    // 重置游戏
    resetTetris();

    // 绑定按钮事件
    document.getElementById('tetris-start').onclick = startTetris;
    document.getElementById('tetris-pause').onclick = pauseTetris;
    document.getElementById('tetris-reset').onclick = resetTetris;

    // 绑定键盘事件
    document.removeEventListener('keydown', handleTetrisKeydown);
    document.addEventListener('keydown', handleTetrisKeydown);

    // 初始绘制（解决黑屏）
    drawTetris();
}

/**
 * 清理俄罗斯方块游戏
 */
function cleanupTetrisGame() {
    clearInterval(tetrisInterval);
    document.removeEventListener('keydown', handleTetrisKeydown);
}